package com.erp.module.yiJianXiang.xJYiJianXiang

import android.app.Activity
import androidx.appcompat.app.AlertDialog
import android.content.Intent
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import com.erp.activity.BaseActivity
import com.erp.activity.DanjianivActivity
import com.erp.myAdapter.ArrayAdapter
import com.erp.myAdapter.TouSuphotoAdapter
import com.erp.bean.TouSuBean
import com.erp.mclass.QuanXian
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.activity.MainKActivity
import com.erp.util.Dialogutil
import com.erp.util.Httputil
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import com.erp.module.yiJianXiang.FragmentYiJianXIang
import kotlinx.android.synthetic.main.activity_tousu.*
import kotlinx.android.synthetic.main.header_knoya.*
import org.json.JSONException
import org.json.JSONObject
import java.util.*

/**
 * Created by Administrator on 2018/2/27/027.
 * 作者：刘洋
 */

class XJYiJianXiangActivity : BaseActivity(), AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {
    private var code = 0
    lateinit var touSuBean: TouSuBean
    private var isxiugai: Boolean = false
    private val isshanchu: Boolean = false
    private var rigcode = 1
    lateinit var deletephoto: MutableList<TouSuBean.photo>
    lateinit var updatedialog: AlertDialog
    lateinit var touSuphotoAdapter: TouSuphotoAdapter
    override fun getLayoutId(): Int {
        activityname = a
        return R.layout.activity_tousu
    }

    override fun initCreate() {
        initView()
        initData()
    }

    private fun initView() {
        deletephoto = ArrayList<TouSuBean.photo>()
        code = intent.getIntExtra("code", code)
        isxiugai = sp.getBoolean("isXiuGaiTouSuJianYi", isxiugai)
        iv_header_left.visibility = View.VISIBLE
        tv_header_title.visibility = View.VISIBLE
        tv_header_title.text = "投诉建议"
        touSuBean = TouSuBean()
        GvTousuPhoto.onItemClickListener = this
        touSuphotoAdapter = TouSuphotoAdapter(touSuBean.photoList, this)
        GvTousuPhoto.adapter = touSuphotoAdapter
        GvTousuPhoto.onItemLongClickListener = this
        iv_header_left.setOnClickListener(this)
        tv_header_right.setOnClickListener(this)
        if(QuanXian.isXiuGaiTouSuTudy){
            LlDutyBumen.visibility=View.VISIBLE
            LlDutuName.visibility=View.VISIBLE
        }
        if(MainKActivity.ZhuanMaiDianid != "0"){
            LlChangQu.visibility = View.GONE
            LlBumen.visibility = View.GONE
        }
        if (code == 2) {
            rigcode = 1
            touSuBean = FragmentYiJianXIang.touSuBean
            touSuphotoAdapter.notifyA(touSuBean.photoList)
            Myutil.settv(touSuBean.chuangqu, TvChangqu)
            Myutil.settv(touSuBean.bumen, TvBumen)
            Myutil.settv(touSuBean.tousu, TvTousu)
            Myutil.settv(touSuBean.jianyi, TvJianyi)
            Myutil.settv(touSuBean.tousu, TvTousu)
            Myutil.settv(touSuBean.jianyi, TvJianyi)
            Myutil.setet(touSuBean.tousu, EtTousu)
            Myutil.setet(touSuBean.jianyi, EtJianyi)
            Myutil.setet(touSuBean.reply, Ethuifu)
            Myutil.settv(touSuBean.reply, Tvhuifu)
            Myutil.setet(touSuBean.duty_name, EtDutyName)
            Myutil.settv(touSuBean.duty_name, TvDutyName)
            Myutil.settv(touSuBean.duty_bumen, TvDutyBumen)
            LlHuifu.visibility=View.VISIBLE
            if (isxiugai) {
                tv_header_right.visibility = View.VISIBLE
                tv_header_right.text = "修改"
            }
        } else if (code == 1) {
            rigcode = 2
            TvChangqu.visibility = View.GONE
            TvBumen.visibility = View.GONE
            TvTousu.visibility = View.GONE
            TvJianyi.visibility = View.GONE
            TvDutyBumen.visibility=View.GONE
            TvDutyName.visibility=View.GONE
            EtTousu.visibility = View.VISIBLE
            EtJianyi.visibility = View.VISIBLE
            SpChangqu.visibility = View.VISIBLE
            SpBumen.visibility = View.VISIBLE
            SpDutyBumen.visibility=View.VISIBLE
            EtDutyName.visibility=View.VISIBLE
            tv_header_right.visibility = View.VISIBLE
            tv_header_right.text = "保存"
            touSuphotoAdapter.isadd(true)
        }
    }

    private fun initData() {
        Httputil.tousubiao(this@XJYiJianXiangActivity, object : OnUserDataInterface {
            override fun onUserData(data: String) {
                Log.d("TAAAG", "data=" + Myutil.decodeUnicode(data))
                val changqus = ArrayList<String>()
                val bumens = ArrayList<String>()
                changqus.add("")
                bumens.add("")
                try {
                    val jo = JSONObject(data)
                    val changqujo = JsonUtil.getjovolue(jo, "han_qu")
                    val chuangqukeys = changqujo.keys()
                    while (chuangqukeys.hasNext()) {
                        val key = chuangqukeys.next() as String
                        changqus.add(key)
                    }
                    val bumenjo = JsonUtil.getjovolue(jo, "bu_men")
                    val bumenkeys = bumenjo.keys()
                    while (bumenkeys.hasNext()) {
                        val key = bumenkeys.next() as String
                        bumens.add(key)
                    }
                    val cqadapter = ArrayAdapter(this@XJYiJianXiangActivity, R.layout.lv_sp_tvitem, changqus)
                    SpChangqu.adapter = cqadapter
                    val bmadapter = ArrayAdapter(this@XJYiJianXiangActivity, R.layout.lv_sp_tvitem, bumens)
                    SpBumen.adapter = bmadapter
                    SpDutyBumen.adapter=bmadapter
                    for (i in changqus.indices) {
                        if (touSuBean.chuangqu == changqus[i]) {
                            SpChangqu.setSelection(i)
                        }
                    }
                    for (i in bumens.indices) {
                        if (touSuBean.bumen == bumens[i]) {
                            SpBumen.setSelection(i)
                        }
                    }
                    for (i in bumens.indices) {
                        if (touSuBean.duty_bumen == bumens[i]) {
                            SpDutyBumen.setSelection(i)
                        }
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }

            }

            override fun onNot(throwable: String) {
                Log.d("TAAAG", "throwable=" + Myutil.decodeUnicode(throwable))
            }
        })
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.iv_header_left -> finish()
            R.id.tv_header_right -> if (rigcode == 1) {
                if(QuanXian.isreplyTouSuJianYi){
                    Tvhuifu.visibility=View.GONE
                    Ethuifu.visibility=View.VISIBLE
                }
                TvChangqu.visibility = View.GONE
                TvBumen.visibility = View.GONE
                TvTousu.visibility = View.GONE
                TvJianyi.visibility = View.GONE
                TvDutyBumen.visibility=View.GONE
                TvDutyName.visibility=View.GONE
                EtTousu.visibility = View.VISIBLE
                EtJianyi.visibility = View.VISIBLE
                SpChangqu.visibility = View.VISIBLE
                SpBumen.visibility = View.VISIBLE
                SpDutyBumen.visibility=View.VISIBLE
                EtDutyName.visibility=View.VISIBLE
                tv_header_right.visibility = View.VISIBLE
                tv_header_right.text = "保存"
                touSuphotoAdapter.isadd(true)
                rigcode = 2
            } else if (rigcode == 2) {
                val tousuBean = TouSuBean()
                tousuBean.id = touSuBean.id
                tousuBean.photoList = touSuBean.photoList
                tousuBean.chuangqu = SpChangqu.selectedItem.toString()
                tousuBean.bumen = SpBumen.selectedItem.toString()
                tousuBean.tousu = EtTousu.text.toString()
                tousuBean.jianyi = EtJianyi.text.toString()
                tousuBean.reply = Ethuifu.text.toString()
                tousuBean.duty_name=EtDutyName.text.toString()
                tousuBean.duty_bumen=SpDutyBumen.selectedItem.toString()
                updatedialog = Myutil.showupdatedialog(this@XJYiJianXiangActivity, "正在上传", false)
                Httputil.setTouSu(this@XJYiJianXiangActivity, code, tousuBean, deletephoto, object : OnUserDataInterface {
                    override fun onUserData(data: String) {
                        Myutil.MyTost("上传成功")
                        Log.d("TAAAG", "data=" + Myutil.decodeUnicode(data))
                        updatedialog.dismiss()
                        if (code == 2) {
                            try {
                                val jo = JSONObject(data)
                                touSuBean.id = JsonUtil.getvolue(jo, "id")
                                touSuBean.chuangqu = JsonUtil.getvolue(jo, "han_qu")
                                touSuBean.bumen = JsonUtil.getvolue(jo, "bu_men")
                                touSuBean.tousu = JsonUtil.getvolue(jo, "complaint")
                                touSuBean.jianyi = JsonUtil.getvolue(jo, "suggestion")
                                touSuBean.ctime = JsonUtil.getvolue(jo, "ctime")
                                touSuBean.creator_name = JsonUtil.getvolue(jo, "creator_name")
                                touSuBean.reply = JsonUtil.getvolue(jo, "reply");
                                touSuBean.duty_bumen = JsonUtil.getvolue(jo, "duty_bumen")
                                touSuBean.duty_name = JsonUtil.getvolue(jo, "duty_name")
                                tousuBean.photoList.clear()
                                val jsp = JsonUtil.getjsvolue(jo, "files")
                                if (jsp != null) {
                                    for (j in 0 until jsp.length()) {
                                        val jop = jsp.get(j) as JSONObject
                                        val photo = TouSuBean.photo()
                                        photo.fid = JsonUtil.getvolue(jop, "fid")
                                        photo.filename = JsonUtil.getvolue(jop, "filename")
                                        photo.uri = JsonUtil.getvolue(jop, "uri")
                                        touSuBean.photoList.add(photo)
                                    }
                                }
                            } catch (e: JSONException) {
                                e.printStackTrace()
                            }

                            val i = Intent()
                            i.putExtra("isxing", false)
                            setResult(Activity.RESULT_OK, i)
                        } else if (code == 1) {
                            val i = Intent()
                            i.putExtra("isxing", true)
                            setResult(Activity.RESULT_OK, i)
                        }
                        finish()
                    }

                    override fun onNot(throwable: String) {
                        Myutil.MyTost("上传失败")
                        updatedialog.dismiss()
                        val reg = "\""
                        val ss = throwable.split(reg.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                        Myutil.MyTost(Myutil.decodeUnicode(ss[1]))
                        Log.d("TAAAG", "throwable=$throwable")
                    }
                })
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null){
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                99 -> {
                    val selectedImage = data.data
                    val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                    val c = contentResolver.query(selectedImage!!, filePathColumns, null, null, null)
                    c!!.moveToFirst()
                    val columnIndex = c.getColumnIndex(filePathColumns[0])
                    val imagePath = c.getString(columnIndex)
                    addphoto(imagePath)
                }
                100 -> {
                    val name = data.getStringExtra("dir")
                    addphoto(name)
                }
            }
        }
    }

    private fun addphoto(name: String) {
        val photo = TouSuBean.photo()
        photo.uri = name
        touSuBean.photoList.add(photo)
        touSuphotoAdapter.notifyA(touSuBean.photoList)
    }


    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        if (position == touSuBean.photoList.size) {
            Dialogutil.photodialog(this@XJYiJianXiangActivity, null)
        } else {
            val intent = Intent(this@XJYiJianXiangActivity, DanjianivActivity::class.java)
            intent.putExtra("url", touSuBean.photoList[position].uri)
            startActivity(intent)
        }
    }


    override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
        val dialog = AlertDialog.Builder(this@XJYiJianXiangActivity)
        dialog.setTitle("提示")
        dialog.setMessage("确定要删除这个照片")
        dialog.setPositiveButton("确定") { dialog, which ->
            deletephoto.add(touSuBean.photoList[position])
            touSuBean.photoList.remove(touSuBean.photoList[position])
            touSuphotoAdapter.notifyDataSetChanged()
        }
        dialog.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
        dialog.show()
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        for (i in touSuBean.photoList.indices) {
            if (touSuBean.photoList[i].fid == "") {
                touSuBean.photoList.removeAt(i)
            }
        }
    }

    companion object {
        private val a = "XingJianTouSuActivity"
    }
}
